using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Ltf.Remoting.TeamFoundation;
using System.Collections;
using Ltf.Remoting.RemoteEvents;

namespace Ltf.MonitorLizard.Forms
{
	[FormType(FormTypes.WorkItemQueries)]

	public partial class WorkItemQueries : Form
	{
		TFServerConnection connection;
		private Workspace workspace;
		private string projectName;

		public int[] SelectedWorkItems = new int[0];

		public WorkItemQueries(string[] pathList, LizardEventArgs args)
			:this (ServerConnections.GetConnectionForPath(pathList[0]),
			ServerConnections.GetConnectionForPath(pathList[0]).GetWorkspace(pathList[0]),
			pathList[0])
		{
			btnOkay.Visible = false;
		}

		public WorkItemQueries(TFServerConnection connection, Workspace workspace,string path)
		{
			InitializeComponent();
			this.connection = connection;
			this.workspace = workspace;
			sortColumnIndex = new Dictionary<ListView, int>();
			sortColumnIndex.Add(lvwWorkItems, 0);
			sortDesc = new Dictionary<ListView, bool>();
			sortDesc.Add(lvwWorkItems, false);

			projectName = workspace.GetTeamProjectForLocalPath(path).Name;

			LoadProjects(workspace);
		}

		public void LoadProjects(Workspace workspace)
		{
			TeamProject[] projects=workspace.VersionControlServer.GetAllTeamProjects(true);

			foreach (TeamProject project in projects)
			{
				TreeNode tn = tvwQueries.Nodes.Add(project.Name);
				tn.ImageKey = "Project";
				tn.SelectedImageKey = "Project";
				tn.Tag = project;
				if (project.Name == projectName)
					tvwQueries.SelectedNode = tn;
			}

		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			Close();
		}

		private void tvwQueries_AfterSelect(object sender, TreeViewEventArgs e)
		{
			TreeNode tn = e.Node;
			
			if (tn.Tag is TeamProject)
			{
				lastQueryProject = tn.Text;
				TeamProject tp=(TeamProject)tn.Tag;
				WorkItemStore wis = new WorkItemStore(connection.TeamFoundationServer);
				StoredQueryCollection sqc = wis.Projects[tp.Name].StoredQueries;
				foreach (StoredQuery sq in sqc)
				{
					TreeNode tnc = tn.Nodes.Add(sq.Name);
					tnc.ImageKey = "Query";
					tnc.SelectedImageKey = "Query";
					tnc.Tag = sq;
				}
				tn.Expand();
				tn.Tag = null;
			}
			else if (tn.Tag is StoredQuery)
			{
				StoredQuery sq = (StoredQuery)tn.Tag;
				RunStoredQuery(sq, tn.Parent.Text);
			}
			else if (tn.Tag==null)
				lastQueryProject = tn.Text;

		}
		private StoredQuery lastQuery = null;
		private string lastQueryProject = null;

		private void RunStoredQuery(StoredQuery sq, string project)
		{
			lastQuery = sq;
			lastQueryProject = project;
			lvwWorkItems.Items.Clear();
			WorkItemStore wis = new WorkItemStore(connection.TeamFoundationServer);
			WorkItemCollection wic = wis.Query(sq.QueryText.Replace("@project", "'" + project + "'"));
			foreach (WorkItem wi in wic)
			{
				ListViewItem lvi = new ListViewItem(new string[] { wi.Id.ToString(), wi.Type.Name,
						wi.Title,wi.Fields[CoreField.AssignedTo].Value.ToString(), wi.State });
				lvwWorkItems.Items.Add(lvi);
				lvi.Tag = wi;
			}
		}
		Dictionary<ListView, int> sortColumnIndex;
		Dictionary<ListView, bool> sortDesc;

		void lsvChanges_ColumnClick(object sender, ColumnClickEventArgs e)
		{
			ListView lv = sender as ListView;
			lv.Columns[sortColumnIndex[lv]].ImageKey = null;
			if (sortColumnIndex[lv] == e.Column)
				sortDesc[lv] = !sortDesc[lv];
			else
			{
				sortDesc[lv] = false;
				sortColumnIndex[lv] = e.Column;
			}
			lv.ListViewItemSorter = (IComparer)new Sorter(sortColumnIndex[lv], sortDesc[lv]);
			lv.Sort();

		}

		private void lvwWorkItems_SelectedIndexChanged(object sender, EventArgs e)
		{

		}

		private void lvwWorkItems_DoubleClick(object sender, EventArgs e)
		{
			if (lvwWorkItems.SelectedItems.Count == 1)
			{
				ListViewItem lvi = lvwWorkItems.SelectedItems[0];
				if (lvi.Tag is WorkItem)
				{
					WorkItem wi = (WorkItem)lvi.Tag;
					LizardWorkItem lwi = new LizardWorkItem(connection, wi);
					lwi.ShowDialog();
					lvi.SubItems[2].Text = wi.Title;
					lvi.SubItems[3].Text = wi.Fields[CoreField.AssignedTo].Value.ToString();
					lvi.SubItems[4].Text = wi.State;
				}

			}
		}

		private void btnOkay_Click(object sender, EventArgs e)
		{
			List<int> selectedItemsList = new List<int>();
			foreach (ListViewItem lvi in lvwWorkItems.SelectedItems)
				selectedItemsList.Add(int.Parse(lvi.Text));

			SelectedWorkItems = selectedItemsList.ToArray();
			Close();
		}

		private void btnNew_Click(object sender, EventArgs e)
		{
			while (cmsNewWorkitem.Items.Count > 0)
				cmsNewWorkitem.Items.RemoveAt(0);

			WorkItemStore wis = new WorkItemStore(connection.TeamFoundationServer);
			WorkItemTypeCollection witc = wis.Projects[lastQueryProject].WorkItemTypes;
			foreach (WorkItemType wit in witc)
			{
				ToolStripItem tsi = cmsNewWorkitem.Items.Add(string.Format("New {0}", wit.Name));
				tsi.Click += new EventHandler(NewWorkItemMenu_Click);
				tsi.Tag = wit;
			}
			cmsNewWorkitem.Show(btnNew,new Point(4,4));
		}

		void NewWorkItemMenu_Click(object sender, EventArgs e)
		{
			if (sender is ToolStripItem)
			{
				ToolStripItem tsi = (ToolStripItem)sender;
				if (tsi.Tag is WorkItemType)
				{
					WorkItemType wit=(WorkItemType)tsi.Tag;
					WorkItem wi = wit.NewWorkItem();
					LizardWorkItem lwi = new LizardWorkItem(connection, wi);
					lwi.ShowDialog();
					if (lastQuery != null)
						RunStoredQuery(lastQuery, lastQueryProject);
				}
			}
		}
	}
}